﻿//功能描述:1:用于YUITreeList模板 负责创建各种树及列表  2:设置对话框的大小
//创建人:zxx
//创建时间:2012-03-16
//修改历史纪录
//版 本  修改时间      修改人            修改内容
//1.00   

//初始化树
var tree1;
//绑定列表
var mDataTable;
// 没有实体
if (typeof (_NoEntity) == "undefined") _NoEntity = "";
function BindData() {
    YAHOO.example.XHR_JSON = function () {
        var formatUrl = function (elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = "<a href='" + oRecord.getData("ClickUrl") + "' target='_blank'>" + sData + "</a>";
        };
        var formatRating = function (elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = (sData === null) ? "N/A" : YAHOO.util.Number.format(sData);
        };
        var myColumnDefs = const_DataFields;
        var url = "http://" + this.location.host + "/Extend/AjaxData/" + _NoEntity + "JSONList.aspx?";
        var myDataSource = new YAHOO.util.DataSource(url);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        myDataSource.connXhrMode = "queueRequests";
        myDataSource.responseSchema = {
            resultsList: "rows",
            metaFields: { totalRecords: "total" },
            fields: const_DataColums
        };
        this.myDataTable = new YAHOO.widget.DataTable("json", myColumnDefs,
                    myDataSource,
                    { initialRequest: initialRequestUrl
                    , selectionMode: "single"
                    });

        //Add by hexingxiang
        GetTotal("http://" + this.location.host + "/Extend/AjaxData/" + _NoEntity + "JSONList.aspx?onlyTotal=true&" + initialRequestUrl);


        mDataTable = this.myDataTable;
        var mySuccessHandler = function () {
            this.set("sortedBy", null);
            this.onDataReturnAppendRows.apply(this, arguments);
        };
        var myFailureHandler = function () {
            this.showTableMessage(YAHOO.widget.DataTable.MSG_ERROR, YAHOO.widget.DataTable.CLASS_ERROR);
            this.onDataReturnAppendRows.apply(this, arguments);
        };
        var callbackObj = {
            success: mySuccessHandler,
            failure: myFailureHandler,
            scope: myDataTable
        };
        // 调用自定义双击行的方法
        var onRowDoubleClick = function () {
            if (typeof (CustomDbClick) == "function") {
                CustomDbClick();
            } else {
                if (typeof (fnView) == "function") {
                    fnView("e");
                }
            }
        };

        // 注册相关方法给相关事件
        this.myDataTable.subscribe("rowMouseoverEvent", this.myDataTable.onEventHighlightRow);
        this.myDataTable.subscribe("rowMouseoutEvent", this.myDataTable.onEventUnhighlightRow);
        this.myDataTable.subscribe("rowClickEvent", this.myDataTable.onEventSelectRow);
        this.myDataTable.subscribe("cellClickEvent", this.myDataTable.onEventShowCellEditor);
        this.myDataTable.subscribe("rowDblclickEvent", onRowDoubleClick);
        this.myDataTable.subscribe("checkboxClickEvent", function (oArgs) {
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            oRecord.setData("iSun_Selected", elCheckbox.checked);
        });
        this.myDataTable.selectRow(this.myDataTable.getTrEl(0));
        hideCol();
        //自定义隐藏列
        if (typeof (customFnHideCol) == "function") {
            customFnHideCol();
        }
    } ();
}
//隐藏/栏位
function hideCol() { mDataTable.hideColumn(parseInt(0)); mDataTable.refreshView(); };


/*关闭窗口*/
function closeWin() {
    //Y.util.Dom.get("yui-gen7-button").setAttribute("style", "display:block");
    YAHOO.example.container.dialog1.hide();
    LoadData();
}
//*****************************************************************分页相关*******************************************************
// 分页方法
var SetPaging = function (total) {
    var Ex = YAHOO.namespace('example');
    Ex.handlePagination = function (state) {
        pageindex = state.page;
        pagesize = Ex.Config.rowsPerPage;
        var requestStr = "pagesize=" + Ex.Config.rowsPerPage + "&pageindex=" + pageindex + "&entity=" + const_entityName + "&order=" + const_Order + "&r=" + Math.random() + "&zip=94089&results=10&output=json&functionid=" + const_functionId + "&customCondition=" + const_CustomCondition + "&condition=" + const_Condition;
        myDataTable.requery(requestStr);
        Ex.paginator.setState(state);
    };

    // Create the Paginator widget and subscribe to its changeRequest event
    Ex.Config = {
        rowsPerPage: 23,
        firstPageLinkLabel: "第一页",
        lastPageLinkLabel: "尾页",
        previousPageLinkLabel: "上一页",
        nextPageLinkLabel: "下一页",
        totalRecords: total,
        containers: 'page'
    };

    Ex.paginator = new YAHOO.widget.Paginator(Ex.Config);
    Ex.paginator.subscribe('changeRequest', Ex.handlePagination);
    Ex.paginator.render();
}

// 获取最新的总数
var GetTotal = function (url) {
    YAHOO.util.Connect.asyncRequest('POST', url, {
        success: function (res) {
            //alert(res.responseText);
            var o = eval(res.responseText);
            //alert(document.getElementById("pagetotal"));
            if (o != undefined) {
                SetPaging(o[0].total);
                if (document.getElementById("pagetotal") != null) {
                    document.getElementById("pagetotal").innerHTML = "<b>共<font color=\"red\">" + o[0].total + "</font>笔记录</b>";
                }
            }
            if (o[0].total == 0) {
                setTimeout('mDataTable.showTableMessage("没有数据", "没有数据")', 500);
            }
        },
        failure: function (error) {
            //alert("数据错误：" + error.statusText);
        }
    }, null);
}
//--分页使用
GetTotal("http://" + this.location.host + "/Extend/AjaxData/" + _NoEntity + "JSONList.aspx?onlyTotal=true&" + initialRequestUrl);


//获取列表选中的值
function Save() {
    var list = this.mDataTable.getRecordSet()._records;
    var elist = [];
    dl = [];
    for (var i = 0; i < list.length; i++) {
        if (list[i]._oData["iSun_Selected"] == true) {
            elist.push(list[i]._oData[const_entityID]);
        }
    }
    //var recordID = mDataTable.getSelectedRows()[0];;
    alert(elist.join(','));
}


function RefreshData() {
    initialRequestUrl = "pageindex=1&entity=" + const_entityName + "&order=" + const_Order + "&r=" + Math.random() + "&zip=94089&results=10&output=json&functionid=" + const_functionId + "&customCondition=" + decodeURI(const_CustomCondition) + "&condition=" + const_Condition;
    pageindex = 1;
    //BindData();
    //RefreshCache();
    ReLoadData();
}

/*刷新时候调用*/
function ReLoadData() {
    //debugger
    var requestStr = "pagesize=" + pagesize + "&pageindex=" + pageindex + "&entity=" + const_entityName + "&order=" + const_Order + "&r=" + Math.random() + "&zip=94089&results=10&output=json&functionid=" + const_functionId + "&customCondition=" + const_CustomCondition + "&condition=" + const_Condition;
    GetTotal("http://" + this.location.host + "/Extend/AjaxData/" + _NoEntity + "JSONList.aspx?onlyTotal=true&" + requestStr);
    mDataTable.requery(requestStr);
    fnCreateChkAllCheckBox();
    //BindData();
}



// 用于数据刷新
YAHOO.widget.DataTable.prototype.requery = function (newRequest) {
    var ds = this.getDataSource();
    if (ds instanceof YAHOO.util.LocalDataSource) {
        ds.liveData = newRequest;
        ds.sendRequest("",
			{
			    success: this.onDataReturnInitializeTable,
			    failure: this.onDataReturnInitializeTable,
			    scope: this
			}
		);
    } else {
        ds.sendRequest(
			(newRequest === undefined ? this.get('initialRequest') : newRequest),
			{
			    success: this.onDataReturnInitializeTable,
			    failure: this.onDataReturnInitializeTable,
			    scope: this
			}
		);
    }
};



//YAHOO.util.Event.addListener(window, "load", BindData);
var _state = "";
YAHOO.namespace("example.container");
YAHOO.util.Event.onDOMReady(function () {
    var handleSubmit = function () {
        var editwindow = document.getElementById("EditUIWindow");
        if (editwindow) {
            if (editwindow.contentWindow.const_entityName == "CrmProductLayout") {
                var id = editwindow.contentWindow.ids;
                var v = SaveCopy(id);
                if (v == 1) {
                    this.cancel();
                }
                return;
            }
            editwindow.contentWindow.Save();
            var src = editwindow.src;
            //alert(src);
            //if (!(src.indexOf("hrEmployee", 0) > -1 || src.indexOf("AutoLoadForm.aspx", 0) > -1)) {
            //     alert("设置成功");
            //     this.cancel();
            //     ReLoadData();
            //}   
        }
        if (_state != "") {
            this.cancel();
        }
    };
    var handleCancel = function () {
        this.cancel();
    };
    var handleSuccess = function (o) {
        var response = o.responseText;
        response = response.split("<!")[0];
        document.getElementById("resp").innerHTML = response;
    };
    var handleFailure = function (o) {
        alert("Submission failed: " + o.status);
    };
    var handleCancel1 = function () {
        this.cancel();
    };
    var callback =
        {
            success: handleSuccess1,
            failure: handleFailure1,
            argument: { foo: "foo", bar: "bar" }
        };
    var handleSubmit1 = function () {
        var editwindow1 = document.getElementById("EditUIWindow1");
        if (editwindow1) {
            editwindow1.contentWindow.Save(fkey);
            alert("设置成功");
            this.cancel();

        }
    };
    var handleSuccess1 = function (o) {
        alert("设置成功");
        this.cancel();
    };
    var handleFailure1 = function (o) {
        alert("操作失败");
    };
    // Remove progressively enhanced content class, just before creating the module
    YAHOO.util.Dom.removeClass("dialog1", "yui-pe-content");
    // Instantiate the Dialog
    YAHOO.example.container.dialog1 = new YAHOO.widget.Dialog("dialog1",
							{ width: const_EditWindowWidth,
							    height: const_EditWindowHeight,
							    fixedcenter: true,
							    draggable: true,
							    close: true,
							    max: true,
							    visible: false,
							    //modal: true,
							    autofillheight: "body",
							    constraintoviewport: true,
							    buttons: [{ text: "保存", handler: handleSubmit, isDefault: true },
								      { text: "取消", handler: handleCancel}]
							});
    YAHOO.util.Dom.removeClass("dialog2", "yui-pe-content");
    YAHOO.example.container.dialog2 = new YAHOO.widget.Dialog("dialog2",
							{ width: "450px",
							    height: "360px",
							    fixedcenter: true,
							    draggable: true,
							    close: true,
							    //modal: true,
							    visible: false,
							    autofillheight: "body",
							    constraintoviewport: true,
							    buttons: [{ text: "保存", handler: handleSubmit1, isDefault: true },
								      { text: "取消", handler: handleCancel1}]
							});

    //删除时用到
    YAHOO.example.container.dialog3 = new YAHOO.widget.Dialog("dialog3",
							    { width: "350px",
							        height: "100px",
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        //modal: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [{ text: "确定", handler: DeleteData, isDefault: true },
								          { text: "取消", handler: handleCancel}]
							    });
    /*
    查询
    */
    YAHOO.example.container.dialog4 = new YAHOO.widget.Dialog("dialog4",
							    { width: "650px",
							        height: "350px",
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        //modal: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [
							    { text: "取消", handler: handleCancel}]
							    });
    YAHOO.example.container.dialog5 = new YAHOO.widget.Dialog("dialog5",
							    { width: const_EditWindowWidth,
							        height: const_EditWindowHeight,
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        //modal: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [
							    { text: "取消", handler: handleCancel}]
							    });



    var handleSubmit6 = function () {
        var editwindow = document.getElementById("EditUIWindow4");
        if (editwindow) {
            editwindow.contentWindow.ChooseInfo();
            this.cancel();
        }

    };
    var handleCancel6 = function () {
        this.cancel();
    };


    YAHOO.util.Dom.removeClass("dialog6", "yui-pe-content");
    YAHOO.example.container.dialog6 = new YAHOO.widget.Dialog("dialog6",
							{ width: "450px",
							    height: "360px",
							    fixedcenter: true,
							    visible: false,
							    draggable: true,
							    close: true,
							    modal: true,
							    constraintoviewport: true,
							    buttons: [{ text: "保存", handler: handleSubmit6, isDefault: true },
								      { text: "取消", handler: handleCancel6}]
							});

    //用户确认操作
    YAHOO.example.container.dialog7 = new YAHOO.widget.Dialog("dialog7",
							    { width: "350px",
							        height: "100px",
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        //modal: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [{ text: "确定", handler: OperationConfig, isDefault: true },
								          { text: "取消", handler: handleCancel}]
							    });
    // Validate the entries in the form to require that both first and last name are entered
    YAHOO.example.container.dialog1.validate = function () {
        var data = this.getData();
        if (data.firstname == "" || data.lastname == "") {
            alert("Please enter your first and last names.");
            return false;
        } else {
            return true;
        }
    };

    YAHOO.example.container.dialog1.callback = { success: handleSuccess,
        failure: handleFailure
    };
    YAHOO.example.container.dialog1.render();
    YAHOO.example.container.dialog2.render();
    YAHOO.example.container.dialog3.render();
    YAHOO.example.container.dialog4.render();
    YAHOO.example.container.dialog6.render();
    YAHOO.example.container.dialog7.render();
    //拖动大小
    var resize = new YAHOO.util.Resize("dialog1", {
        handles: ["br"],
        autoRatio: false,
        minWidth: 450,
        minHeight: 400,
        status: false
    });
    resize.on("startResize", function (args) {

        if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;

            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);

            resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize.set("maxWidth", null);
            resize.set("maxHeight", null);
        }

    }, YAHOO.example.container.dialog1, true);
    resize.on("resize", function (args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, YAHOO.example.container.dialog1, true);
    //YAHOO.util.Event.addListener("hide", "click", YAHOO.example.container.dialog1.hide, YAHOO.example.container.dialog1, true);
});

/* 对应的方法和ID*/
var _fn, _id;
function ShowDialog(fn, id, src) {
    _fn = fn;
    _id = id;
    document.getElementById("EditUIWindow4").src = src;
    YAHOO.example.container.dialog6.show();
}

// 设置对话框的大小
var SetDWH = function (width, height, dialog) {
    var elements = YAHOO.util.Dom.getElementsByClassName('bd', 'div')[0];
    var w = [],
        h = [];
    w.push(width);
    h.push(height);
    dialog.configWidth(null, w);
    dialog.configHeight(null, h);

    dialog.render();
    if (elements) {
        dialog.fillHeight(elements);
    }
}
// 设窗口最大化
var SetMaxDWH = function (dialog) {
    var w = Y.util.Dom.getViewportWidth() - 20;
    var h = Y.util.Dom.getViewportHeight() - 20;
    SetDWH(w, h, dialog);
}

var SetNorDWH = function (dialog) {

}

var fnCreateChkAllCheckBox = function () {
    if ((document.getElementById("chkAll")) == null) {
        var e1 = window.document.getElementById("yui-dt16-th-iSun_Selected");
        if (e1 == null) {
            e1 = window.document.getElementById("yui-dt27-th-iSun_Selected");
        }
        if (e1 == null) {
            return;
        }
        if (typeof (e1) != "undefined") {
            var in1 = e1.firstChild;
            var el = document.createElement("input");
            el.setAttribute("type", "checkbox");
            el.setAttribute("id", "chkAll");
            el.setAttribute("onclick", "fnChkAll()");
            el.setAttribute("style", "margin-left:0px;margin-top:0px;z-index:200")
            in1.insertBefore(el);
        }
    }
}
